package com.demo2do.fms.admin.service.report.impl;

import java.io.File;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.page.Page;
import com.demo2do.core.persistence.annotation.Dao;
import com.demo2do.core.utils.DateFormatUtils;
import com.demo2do.core.utils.StringUtils;
import com.demo2do.fms.admin.dao.report.DriverCostAppointmentDao;
import com.demo2do.fms.admin.dao.supplier.OrganizationDao;
import com.demo2do.fms.admin.service.DataServiceImpl;
import com.demo2do.fms.admin.service.report.DriverCostAppointmentService;
import com.demo2do.fms.entity.authority.Organization;
import com.demo2do.fms.entity.report.DriverCostAppointment;

/**
 *
 * @author Ark
 *
 */
@Service("driverCostAppointmentService")
public class DriverCostAppointmentServiceImpl extends DataServiceImpl<DriverCostAppointment> implements DriverCostAppointmentService {

    @Value("#{config['appointment.dailylimit']}")
    private int dailyLimit;
    
    @Value("#{config['appointment.csv.path']}")
    private String csvPath;
    
    @Dao
    private DriverCostAppointmentDao driverCostAppointmentDao;
    
    @Dao
    private OrganizationDao organizationDao;
    
    /* (non-Javadoc)
     * @see com.demo2do.fms.admin.service.report.DriverCostAppointmentService#count(java.util.List)
     */
    public int count(List<Long> orgIds) {
        return driverCostAppointmentDao.count(orgIds);
    }
    
    /* (non-Javadoc)
     * @see com.demo2do.fms.admin.service.report.DriverCostAppointmentService#list(java.util.List, com.demo2do.core.entity.page.Page)
     */
    public List<DriverCostAppointment> list(List<Long> orgIds, Page page) {
        List<DriverCostAppointment> result = driverCostAppointmentDao.list(orgIds, page.getBeginIndex(), page.getEveryPage());
        page.calculate();
        return result;
    }
    
    /* (non-Javadoc)
     * @see com.demo2do.fms.admin.service.report.DriverCostAppointmentService#create(com.demo2do.fms.entity.report.DriverCostAppointment, java.lang.Long)
     */
    public void create(DriverCostAppointment appointment, Long operator) {

        // 1. check whether reach the_upper_limit of daily_number
        String date = DateFormatUtils.today();
        int dailyNumbers = driverCostAppointmentDao.count(appointment.getOrganizationId(), date);
        if (dailyNumbers >= dailyLimit) {
            throw BusinessException.newInstance("400", "已达预约上限，一家运输公司一天最多只能预约" + dailyLimit + "次");
        }
        
        // 2. save
        Organization organization = organizationDao.load(appointment.getOrganizationId());
        genericDaoSupport.save(appointment.initialize(organization, operator));
        
    }
    
    /* (non-Javadoc)
     * @see com.demo2do.fms.admin.service.report.DriverCostAppointmentService#delete(com.demo2do.fms.entity.report.DriverCostAppointment, java.lang.Long)
     */
    public void delete(DriverCostAppointment appointment, Long operator) {
        
        // 1. validate
        if (!appointment.getCreator().equals(operator)) {
            throw BusinessException.newInstance("500", "此操作仅限预约创建人执行");
        }
        
        if (appointment.getStatus().isProcessing()) {
            throw BusinessException.newInstance("500", "此预约已开始处理，无法删除");
        }
        
        // 2. delete file
        this.deleteFile(appointment.getUrl());
        
        // 3. delete
        genericDaoSupport.delete(appointment.delete(operator));
        
    }
    
    /**
     * 删除csv文件
     * 
     * @param url
     */
    private void deleteFile(String url) {
        
        if (org.apache.commons.lang3.StringUtils.isNotBlank(url)) {
            
            String filename = FilenameUtils.getName(url);
            String pathname = StringUtils.connect(csvPath, "/", filename);
            File csvFile = new File(pathname);
            
            if (csvFile.exists()) {
                FileUtils.deleteQuietly(csvFile);
            }
            
        }
        
    }
    
}
